#include <stdio.h>
#include <stdlib.h>
/*1->2->1->3->1->1->5 */
struct slist {
	struct slist *m_next;
	int m_val;
};

void print_list(struct slist *head)
{
	while (head) {
		printf("%d --->", head->m_val);
		head = head->m_next;
	}
	printf("NULL\n");
}
struct slist *add_node_sorted(struct slist *head, struct slist *node)
{
	struct slist **p = NULL;
	if (head == NULL) return node;
	for (p = &head; *p; p =&(*p)->m_next) { 
		if (node->m_val < (*p)->m_val) {
			node->m_next = *p;
			*p = node;
			break;
		}
	}
	*p = node;
	return head;
}

struct slist *create_list(int *array, int len)
{
	int i;
	struct slist *head = NULL, *node = NULL, *tail = NULL;
	for (i = 0; i < len; i++) {
		node = (struct slist *)malloc(sizeof(struct slist));
		node->m_val = array[i];
		node->m_next = NULL;
		if (head == NULL) {
			tail = head = node;
	
		} else {
			tail->m_next = node;
			tail = node;
		}
	}
	return head;
}

struct slist *create_sorted_list(int *array, int len)
{
	int i;
	struct slist *head = NULL, *node = NULL, *tail = NULL;
	for (i = 0; i < len; i++) {
		node = (struct slist *)malloc(sizeof(struct slist));
		node->m_val = array[i];
		node->m_next = NULL;
		head = add_node_sorted(head, node);
	}
	return head;
}

struct slist *del_node_by_value(struct slist *head, int val)
{
	struct slist *prev = NULL, *pcur = NULL;
	if (head == NULL) return head;
	while (head && head->m_val == val) {
		pcur = head;
		head = head->m_next;
		pcur->m_next = NULL;
		free(pcur);
	}
	if (head == NULL) return head;
	prev = head;
	pcur = head->m_next;
	while (pcur) {
		if (pcur->m_val == val) {
			prev->m_next = pcur->m_next;
			pcur->m_next = NULL;
			free(pcur);
			pcur = prev->m_next;
		} else {
			prev = pcur;
			pcur = pcur->m_next;
		}	
	}
	return head;
}
struct slist *del_node(struct slist *head, int val)
{
	struct slist **p = &head, *p_del = NULL;
	while (*p) { 
		if ((*p)->m_val == val) {
			p_del = *p;
			*p = (*p)->m_next;
			free(p_del);
		} else {
			p = &(*p)->m_next;
		}
	}
	return head;
}

struct slist *reverse(struct slist *head)
{
	if (head == NULL || head->m_next == NULL) return head;
	struct slist *p = head->m_next, *n = NULL;
	head->m_next = NULL;
	while (p) {
		n = p;
		p = p->m_next;
		n->m_next = head;
		head = n;
	}
	return head;
}

void main(void)
{
	int i;
	int array[] = {1, 2, 3, 1, 1, 4, 5, 1, 6, 1};
	struct slist *head = create_sorted_list(array, sizeof(array)/sizeof(int));
	print_list(head);
	head = reverse(NULL);
	print_list(head);
	for (i = 1; i < 8; i++) {
		head = del_node_by_value(head, i);
		print_list(head);
	}

	head = create_list(array, sizeof(array)/sizeof(int));
	head = del_node_by_value(head, 1);
	//head = del_node_for(head, 1);
	print_list(head);
	head = del_node(head, 2);
	print_list(head);
	for (i = 1; i < 8; i++) {
		head = del_node(head, i);
		print_list(head);
	}
	return;
}
